package com.apes.framework.config.jackson;

import com.apes.framework.util.DateUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.util.Date;

public class CustomDateDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String source = jsonParser.getText();
        try {
            if ( source == null )  return null;
            if (source.length() == 0) {
                return null;
            } else {
                if (source.length() < 11) {
                    return DateUtil.parse(source);
                } else {
                    return DateUtil.parseTimestamp(source);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Invalid date format: " + source);
        }
    }
}
